package com.lemeng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.lemeng.dao.*;
import com.lemeng.entity.ImageItem;
import com.lemeng.entity.PageResult;
import com.lemeng.pojo.Album;
import com.lemeng.pojo.OrderItem;
import com.lemeng.pojo.StockBack;
import com.lemeng.service.AlbumService;
import com.lemeng.service.StockBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = StockBackService.class)
public class StockBackServiceImpl implements StockBackService {

    @Autowired
    StockBackMapper stockBackMapper;
    @Autowired
    SkuMapper skuMapper;

    @Override
    public void addBackInfo(List<OrderItem> orderItemList) {

        for (OrderItem orderItem : orderItemList) {

            StockBack stockBack = new StockBack();

            stockBack.setStatus("0");
            stockBack.setSkuId(orderItem.getSkuId());
            stockBack.setOrderId(orderItem.getOrderId());
            stockBack.setNum(orderItem.getNum());
            stockBack.setBackTime(new Date());

            stockBackMapper.insert(stockBack);
        }
    }

    @Override
    public void doBack() {

        //1.查出要回滚的数据信息
        StockBack search = new StockBack();
        search.setStatus("0");
        List<StockBack> stockBacks = stockBackMapper.select(search);

        //2.执行回滚逻辑
        for (StockBack stockBack : stockBacks) {
            skuMapper.addSaleNum(stockBack.getSkuId(),stockBack.getNum()*-1);
            skuMapper.koujiankucun(stockBack.getSkuId(),stockBack.getNum()*-1);

            //3.更新回滚状态
            stockBack.setStatus("1");
            stockBack.setBackTime(new Date());

            stockBackMapper.updateByPrimaryKeySelective(stockBack);
        }
    }
}
